import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || '',
    isLoggedIn: !!localStorage.getItem('token'),
    currentStation: null, // 当前站点信息（站点管理员使用）
    items: [], // 回收物品列表
    orders: [], // 订单列表
    stations: [], // 站点列表
    cart: [] // 购物车（暂存要回收的物品）
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
      state.isLoggedIn = !!token
      if (token) {
        localStorage.setItem('token', token)
        if (state.user && state.user.role) {
          localStorage.setItem('userRole', state.user.role)
        }
      } else {
        localStorage.removeItem('token')
        localStorage.removeItem('userRole')
      }
    },
    SET_CURRENT_STATION(state, station) {
      state.currentStation = station
    },
    SET_ITEMS(state, items) {
      state.items = items
    },
    SET_ORDERS(state, orders) {
      state.orders = orders
    },
    SET_STATIONS(state, stations) {
      state.stations = stations
    },
    LOGOUT(state) {
      state.user = null
      state.token = ''
      state.isLoggedIn = false
      state.currentStation = null
      state.cart = []
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('userId')
      localStorage.removeItem('userName')
    },
    ADD_TO_CART(state, item) {
      // 检查购物车中是否已存在该物品
      const existingItem = state.cart.find(cartItem => cartItem.id === item.id)
      if (!existingItem) {
        state.cart.push({
          ...item,
          quantity: item.unit === 'kg' ? 1.0 : 1
        })
      }
    },
    REMOVE_FROM_CART(state, itemId) {
      const index = state.cart.findIndex(item => item.id === itemId)
      if (index > -1) {
        state.cart.splice(index, 1)
      }
    },
    CLEAR_CART(state) {
      state.cart = []
    },
    UPDATE_CART_ITEM_QUANTITY(state, { itemId, quantity }) {
      const item = state.cart.find(cartItem => cartItem.id === itemId)
      if (item) {
        item.quantity = quantity
      }
    }
  },
  actions: {
    async login({ commit }, credentials) {
      // 使用新的API系统
      const { authAPI } = await import('@/api')
      const response = await authAPI.login(credentials)
      
      // 保存用户信息到localStorage
      if (response.user) {
        localStorage.setItem('userId', response.user.id)
        localStorage.setItem('userName', response.user.realName || response.user.username)
        localStorage.setItem('userRole', response.user.role)
      }
      
      commit('SET_USER', response.user)
      commit('SET_TOKEN', response.token)
      return response
    },
    logout({ commit }) {
      commit('LOGOUT')
    },
    // 初始化用户状态（从localStorage恢复）
    initializeAuth({ commit }) {
      const token = localStorage.getItem('token')
      const userRole = localStorage.getItem('userRole')
      const userId = localStorage.getItem('userId')
      const userName = localStorage.getItem('userName')
      
      if (token && userRole) {
        // 构造用户信息
        const user = {
          id: userId ? parseInt(userId) : null,
          username: userName || '',
          realName: userName || '',
          role: userRole,
          email: '',
          phone: '',
          address: ''
        }
        
        commit('SET_USER', user)
        commit('SET_TOKEN', token)
      }
    },
    async fetchItems({ commit }) {
      // 使用新的API系统
      const { itemsAPI } = await import('@/api')
      const response = await itemsAPI.getItems()
      const items = response.list || response
      commit('SET_ITEMS', items)
      return items
    },
    async fetchOrders({ commit }) {
      // 使用新的API系统
      const { ordersAPI } = await import('@/api')
      const response = await ordersAPI.getOrders()
      const orders = response.list || response
      commit('SET_ORDERS', orders)
      return orders
    }
  },
  getters: {
    isAdmin: state => state.user && state.user.role === 'admin',
    isStationManager: state => state.user && state.user.role === 'station_manager',
    isCustomer: state => state.user && state.user.role === 'customer',
    userRole: state => state.user ? state.user.role : '',
    userName: state => state.user ? (state.user.realName || state.user.username) : '',
    cartItems: state => state.cart,
    cartItemCount: state => state.cart.length
  }
})

